package org.example.com.service.impl;

import org.example.com.mapper.PostCommentMapper;
import org.example.com.mapper.PostMapper;
import org.example.com.pojo.PostComment;
import org.example.com.pojo.vo.PostCommentVO;
import org.example.com.service.PostCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 帖子评论Service实现类
 */
@Service
public class PostCommentServiceImpl implements PostCommentService {
    
    @Autowired
    private PostCommentMapper postCommentMapper;
    
    @Autowired
    private PostMapper postMapper;
    
    @Override
    @Transactional
    public PostComment addComment(PostComment comment) {
        comment.setStatus("active");
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        
        int result = postCommentMapper.insert(comment);
        if (result > 0) {
            // 增加帖子评论数
            postMapper.incrementCommentCount(comment.getPostId());
            return comment;
        }
        
        return null;
    }
    
    @Override
    public List<PostCommentVO> getCommentsByPostId(Integer postId, Integer page, Integer limit) {
        int offset = (page - 1) * limit;
        return postCommentMapper.selectByPostId(postId, offset, limit);
    }
    
    @Override
    public PostComment getCommentById(Integer id) {
        return postCommentMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public boolean updateComment(PostComment comment) {
        comment.setUpdatedAt(LocalDateTime.now());
        return postCommentMapper.update(comment) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteComment(Integer id) {
        PostComment comment = postCommentMapper.selectById(id);
        if (comment != null) {
            // 减少帖子评论数
            postMapper.decrementCommentCount(comment.getPostId());
            return postCommentMapper.deleteById(id) > 0;
        }
        return false;
    }
}
